package eproject.mm.com.projectsupervision.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.List;
import java.util.Map;

import eproject.mm.com.projectsupervision.MainActivity;
import eproject.mm.com.projectsupervision.PrjApplication;
import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.adapter.DataAdapter;
import eproject.mm.com.projectsupervision.service.UpdateService;
import eproject.mm.com.projectsupervision.util.HttpUtil;
import eproject.mm.com.projectsupervision.util.MobileInfoUtils;

public class LoginActivity extends Activity {
    Button btn_login;
    EditText et_username;
    EditText et_password;
    SharedPreferences userSettings;
    CheckBox cb_autologin;
    TextView tv_serverSetting;

    LoadingDialog loadingDialog = null;
    TextView tv_selfStart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        tv_selfStart = (TextView)findViewById(R.id.tv_selfStart);
        btn_login = (Button) findViewById(R.id.btn_login);
        et_username = (EditText)findViewById(R.id.et_username);
        et_password = (EditText)findViewById(R.id.et_password);
        cb_autologin = (CheckBox)findViewById(R.id.cb_autologin);

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doLogin();
            }
        });
        tv_serverSetting = (TextView)findViewById(R.id.tv_serverSetting);
        tv_serverSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, ServerSettingActivity.class);
                startActivityForResult(intent,1000);
            }
        });

        userSettings = getSharedPreferences("setting", Context.MODE_MULTI_PROCESS);
        String username = userSettings.getString("username","");
        String password = userSettings.getString("password","");
        String autoload = userSettings.getString("autoload","0");

        if(autoload.equals("1")){
            et_username.setText(username);
            et_password.setText(password);
            cb_autologin.setChecked(true);
        }

        String serverip = userSettings.getString("serverip","");
        String serverport = userSettings.getString("serverport","");

        PrjApplication.getInstance().setServerIp(serverip);
        PrjApplication.getInstance().setServerPort(serverport);

        TextView tv_version = (TextView)findViewById(R.id.tv_version);
        tv_version.setText(PrjApplication.getInstance().getVersion());

        tv_selfStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobileInfoUtils.jumpStartInterface(LoginActivity.this);
            }
        });
    }

    private void doLogin(){
        final String _str_username = et_username.getText().toString().trim();
        final String _str_password = et_password.getText().toString().trim();

        if(_str_username.equals("")){
            Toast.makeText(this,"用户名不能为空",Toast.LENGTH_SHORT).show();
            return;
        }

//        startActivity(new Intent(LoginActivity.this, MainActivity.class));
//        finish();
//        return;

        loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("加载中...").show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String resultStr = HttpUtil.get("/login?username="+_str_username+"&password="+_str_password+"&phoneType="+Build.MANUFACTURER);

                    handler.sendMessage(handler.obtainMessage(1, resultStr));
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this,e.toString(),Toast.LENGTH_LONG);
                    handler.sendMessage(handler.obtainMessage(2, null));
                }
            }
        }).start();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1000:
                if(resultCode == RESULT_OK){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Bundle bundle = data.getExtras();
                            String serverip = bundle.getString("serverip","");
                            String serverport = bundle.getString("serverport","");

                            PrjApplication.getInstance().setServerIp(serverip);
                            PrjApplication.getInstance().setServerPort(serverport);
                        }
                    });
                }
                break;
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String str = (String)msg.obj;
                    Gson gson=new Gson();
                    Map resultMap = gson.fromJson(str, Map.class);
                    if (resultMap != null && (boolean) resultMap.get("success")) {
                        String version = (String)resultMap.get("version");
                        if(version == null){
                            version = "0";
                        }
                        String appVersion = PrjApplication.getInstance().getVersion();
                        if(appVersion == null){
                            appVersion = "0";
                        }
                        if(appVersion.compareTo(version)<0){
                            loadingDialog.close();
                            btn_login.setEnabled(false);
                            Toast.makeText(LoginActivity.this, "当前版本:"+appVersion+",存在新版本:"+version+",自动升级", Toast.LENGTH_LONG).show();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    //启动服务
                                    Intent service = new Intent(LoginActivity.this,UpdateService.class);
                                    startService(service);
                                }
                            }).start();
                        }else {
                            SharedPreferences.Editor editor = userSettings.edit();
                            String userId = (String) resultMap.get("id");
                            String name = (String) resultMap.get("name");
                            String orgId = (String) resultMap.get("orgid");
                            String orgName = (String) resultMap.get("orgname");

                            PrjApplication.getInstance().setAuthenticationToken(userId);
                            PrjApplication.getInstance().setUserName(name);
                            PrjApplication.getInstance().setOrgName(orgName);

                            editor.putString("authenticationtoken", userId);
                            //loadingDialog.close();
                            editor.putString("username", et_username.getText().toString().trim());
                            editor.putString("username", et_username.getText().toString().trim());

                            if (cb_autologin.isChecked()) {
                                editor.putString("username", et_username.getText().toString().trim());
                                editor.putString("password", et_password.getText().toString().trim());
                                editor.putString("autoload", "1");
                            } else {
                                editor.remove("username");
                                editor.remove("password");
                                editor.putString("autoload", "0");
                            }
                            editor.commit();
                            PrjApplication.getInstance().setLogin(true);
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            loadingDialog.close();
                            finish();
                        }
                    }else if(resultMap != null){
                        PrjApplication.getInstance().setLogin(false);
                        loadingDialog.close();
                        Toast.makeText(LoginActivity.this,(String)resultMap.get("message"),Toast.LENGTH_LONG).show();
                    }
                    break;
                case 2:
                    PrjApplication.getInstance().setLogin(false);
                    loadingDialog.close();
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };

    @Override
    protected void onRestart() {
        super.onRestart();
        //Intent intent = new Intent(LoginActivity.this,MainActivity.class);
        //startActivity(intent);
        //overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
        //finish();
    }
}
